package com.soft.servlet;

import com.soft.entity.TrolleyInfo;
import com.soft.entity.UserInfo;
import com.soft.service.Domain;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author kongz
 * @version 1.0 2021/6/2 17:02
 * @description 购物车显示servlet
 */
 @WebServlet(name = "GouWuCheListServlet", urlPatterns = "/GouWuCheList")
public class GouWuCheListServlet extends HttpServlet {

    private Domain domain;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        domain = new Domain();
        UserInfo ui = null;

        if (req.getSession().getAttribute("user") != null) {
            ui = (UserInfo) req.getSession().getAttribute("user");
            List<TrolleyInfo> list = domain.getTrolleyInfoByUser(ui.getId());
            req.setAttribute("sumPrice", SumPrice(list));
            req.setAttribute("TrolleyInfo", list);
            req.getRequestDispatcher("gouwuche.jsp").forward(req, resp);
        } else {
            req.getSession().setAttribute("flag", 11);
            resp.sendRedirect("denglu.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        domain = new Domain();
        if (req.getParameter("id") != null) {
            int id = Integer.parseInt(req.getParameter("id"));
            String count = req.getParameter("count");

            TrolleyInfo ti = domain.getTrolleyInfoById(id);
            ti.setCount(count);
            domain.updateTrolleyInfo(ti);
            doGet(req, resp);
        }
    }

    private double SumPrice(List<TrolleyInfo> list) {
        double sum = 0.0;
        for (TrolleyInfo ti : list) {
            sum += ti.getPrice();
        }

        return sum;
    }
}
